<template>
  <div class="execution">
    <basic-container>
      <avue-crud ref="crud" :page.sync="page" @on-load="getList" :table-loading="tableLoading" @refresh-change="refreshChange" :option="spuTableOption" :data="spuList">
        <!--添加商品-->
        <template slot-scope="scope" slot="menuLeft">
          <el-button type="success" icon="el-icon-plus" @click.stop="handleAddSpu"> 添 加 商 品</el-button>
        </template>
        <template slot="img" slot-scope="scope">
          <el-image
            @click="handleShow(scope.row, scope.index)"
            style="width: 120px; height: 120px"
            :src="scope.row.imageList[0].imgUrl"
            fit="contain"></el-image>
        </template>
        <template slot="publishStatus" slot-scope="scope">
          <el-switch v-model="scope.row.publishStatus" @change="handleChangeStatus(scope.row)" :active-value="1"
                     :inactive-value="0"></el-switch>
        </template>
        <template slot="expand" slot-scope="scope">
          <el-form label-position="left" class="demo-table-expand">
            <el-form-item label-position="top" label="商品名称">
              <span>{{ scope.row.spuName }}</span>
            </el-form-item>
            <el-form-item label="商品图册">
              <el-image
                v-for="item in scope.row.imageList"
                @click="changeAlbum(scope.row)"
                style="width: 120px; height: 120px; margin: 0 10px 0 10px;"
                :src="item.imgUrl"
                :preview-src-list="albumList"
                fit="contain" lazy></el-image>
            </el-form-item>
            <el-form-item label="商品描述">
              <span>{{ scope.row.spuDescription }}</span>
            </el-form-item>
          </el-form>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button @click="handleShowSKU(scope.row, scope.index)" icon="el-icon-present" :size="scope.size"
                     :type="scope.type">SKU
          </el-button>
          <el-button @click="handleEdit(scope.row, scope.index)" icon="el-icon-edit" :size="scope.size"
                     :type="scope.type">编辑
          </el-button>
          <el-button @click="handleDel(scope.row,scope.index)" icon="el-icon-delete" :size="scope.size"
                     :type="scope.type">删除
          </el-button>
        </template>
      </avue-crud>
      <el-dialog
        title="详情预览"
        :visible.sync="detailDialogVisible"
        width="30%">
        <div v-for="item in detailImgUrlList">
          <el-image :src="item" fit="contain">
            <div slot="placeholder" class="image-slot">
              加载中<span class="dot">...</span>
            </div>
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="detailDialogVisible = false">关 闭</el-button>
        </span>
      </el-dialog>

      <!--sku管理-->
      <el-dialog
        title="sku 管理"
        :visible.sync="skuDialogVisible"
        width="80%">
        <avue-crud :data="skuList" :option="skuTableOption" :page.sync="skuPage" @on-load="getSkuList">
          <template slot="skuDefaultImg" slot-scope="scope">
            <el-image
              style="width: 120px; height: 120px"
              :src="scope.row.skuDefaultImg"
              fit="contain"></el-image>
          </template>
        </avue-crud>
        <span slot="footer" class="dialog-footer">
          <el-button @click="skuDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="skuDialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>

      <!-- todo 添加商品 -->
      <el-dialog
        title="添 加 商 品"
        :visible.sync="addSpuDialogVisible"
        width="70%">
        <el-steps style="padding: 0 40px 0 40px;" :active="addSpuActive" finish-status="success">
          <el-step title="基本信息"></el-step>
          <el-step title="规格参数"></el-step>
          <el-step title="销售属性"></el-step>
          <el-step title="SKU信息"></el-step>
        </el-steps>
        <el-card class="box-card" style="width:80%; margin:20px auto">
          <!-- 第一步: 基本信息 -->
          <el-form v-show="addSpuActive===0" ref="spuBaseInfoForm" :model="spu" :rules="baseInfoRule"
                   label-width="100px">
            <el-form-item label="商品名称" prop="spuName">
              <el-input style="width: 240px;" placeholder="请输入 商品名称" v-model="spu.spuName"></el-input>
            </el-form-item>
            <el-form-item label="商品描述">
              <el-input style="width: 240px;" placeholder="请输入 商品描述" v-model="spu.spuDescription"
                        type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="选择分类" prop="categoryId">
              <el-cascader
                placeholder="请选择 分类"
                style="width: 180px;"
                v-model="spu.categoryId"
                :options="categoryList"
                @change="handleChange"></el-cascader>
            </el-form-item>
            <el-form-item label="选择品牌" prop="brandId">
              <el-select style="width: 180px;" v-model="spu.brandId" placeholder="请选择 品牌">
                <el-option
                  v-for="item in brandList"
                  :key="item.brandId"
                  :label="item.name"
                  :value="item.brandId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品重量">
              <el-input-number v-model.number="spu.weight" :min="0" :precision="3" :step="0.1"/>
              <span style="margin-left: 8px; color: black; font-weight: 700;">Kg</span>
            </el-form-item>
            <el-form-item label="设置积分">
              <label style="margin-right: 8px; color: #409eff;">金币:</label>
              <el-input-number
                placeholder="金币"
                v-model="spu.bounds.buyBounds"
                :min="0"
              />
              <label style="margin-left:15px; margin-right: 8px; color: #409eff;">成长值:</label>
              <el-input-number
                placeholder="成长值"
                v-model="spu.bounds.growBounds"
                :min="0"
              />
            </el-form-item>
            <el-form-item label="商品介绍" prop="description">
              <multi-upload v-model="spu.description"></multi-upload>
            </el-form-item>
            <el-form-item label="商品图集" prop="images">
              <multi-upload v-model="spu.images"></multi-upload>
            </el-form-item>
            <el-form-item>
              <el-button style="margin: 20px 0 0 120px;" @click="setBaseAttr" size="medium" type="primary">下一步: 设置基本参数
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 第二步: 规格参数 -->
          <el-form v-show="addSpuActive===1" ref="form" :model="spu" label-width="140px">
            <h3 v-for="(group, gid) in baseAttrForm">
              {{ group.label }}
              <el-divider></el-divider>
              <el-form-item
                :key="attr.attrId"
                :label="attr.label + ':'"
                v-for="(attr, cid) in group.column"
                style="width: 100%;">
                <el-select
                  style="width: 200px;"
                  :multiple="attr.type === 'multiple'"
                  filterable
                  allow-create
                  default-first-option
                  v-model="baseAttrForm[gid].column[cid].attrValues"
                  :placeholder="'请选择 ' + attr.label">
                  <el-option
                    v-for="select in attr.dicData"
                    :key="select.value"
                    :label="select.label"
                    :value="select.value">
                  </el-option>
                </el-select>
                <el-checkbox
                  style="margin-left: 10px;"
                  v-model="baseAttrForm[gid].column[cid].isShow"
                  :true-label="1"
                  :false-label="0"
                >快速展示
                </el-checkbox>
              </el-form-item>
            </h3>
            <el-form-item style="margin-top: 40px;">
              <el-button @click="addSpuActive--" size="medium">上一步</el-button>
              <el-button @click="setSaleAttr" size="medium" type="primary">下一步: 设置销售属性</el-button>
            </el-form-item>
          </el-form>

          <!-- 第三步: 设置销售属性 -->
          <el-form v-show="addSpuActive===2" ref="form" :model="spu" label-width="100px">
            <h3>
              <el-form-item
                v-for="(attr, sid) in saleAttrForm"
                :key="attr.attrId"
                :label="attr.label + ':'"
                style="width: 100%;">
                <el-input
                  v-model="tempSaleAttrs[sid].attrId"
                  type="hidden"
                  v-show="false"
                ></el-input>
                <el-checkbox-group v-model="tempSaleAttrs[sid].attrValues">
                  <el-checkbox
                    v-if="attr.valueSelect!==''"
                    :label="checkValue"
                    :key="checkValue"
                    v-for="checkValue in attr.valueSelect.split(';')"
                  >{{ checkValue }}
                  </el-checkbox>
                  <span style="margin-left: 5px;">
                    <el-button
                      style="color: #7EBE50;"
                      v-show="!inputVisible[sid].view"
                      size="mini"
                      @click="showInput(sid)"
                    >+自定义
                    </el-button>
                    <el-input
                      v-show="inputVisible[sid].view"
                      v-model="inputValue[sid].val"
                      :ref="'saveTagInput'+sid"
                      size="mini"
                      style="width:150px"
                      @keyup.enter.native="handleInputConfirm(sid)"
                      @blur="handleInputConfirm(sid)"
                    ></el-input>
                  </span>
                </el-checkbox-group>
              </el-form-item>
              <el-divider></el-divider>
            </h3>
            <el-form-item style="margin-top: 40px; margin-left: 60px;">
              <el-button @click="addSpuActive--" size="medium">上一步</el-button>
              <el-button @click="generateSku" size="medium" type="primary">下一步: 设置SKU信息</el-button>
            </el-form-item>
          </el-form>

          <!-- 第四步: 设置SKU信息 -->
          <div v-show="addSpuActive===3">
            <el-table :data="spu.skus">
              <el-table-column label="商品名称" prop="skuName" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.skuName"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="标题" prop="skuTitle" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.skuTitle"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="副标题" prop="skuSubtitle" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.skuSubtitle"></el-input>
                </template>
              </el-table-column>

              <el-table-column label="属性组合" align="center">
                <el-table-column
                  align="center"
                  :label="item.attrName"
                  :key="item.attrId"
                  v-for="(item, index) in generateSkuTable">
                  <template slot-scope="scope">
                    <span>{{ scope.row.attr[index].attrValue }}</span>
                  </template>
                </el-table-column>
              </el-table-column>

              <el-table-column label="价格" prop="price" align="center">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.price"></el-input>
                </template>
              </el-table-column>

            </el-table>
            <div style="margin-top: 70px; margin-left: 320px;">
              <el-button @click="addSpuActive--" size="medium">上一步</el-button>
              <el-button @click="submitSkus" icon="el-icon-check" size="medium" type="success">下一步: 保存商品信息</el-button>
            </div>
          </div>

        </el-card>
      </el-dialog>

      <el-dialog
        title="修 改 商 品"
        :visible.sync="editSpuDialogVisible"
        width="70%">
        <el-form ref="spuBaseInfoForm" :model="spu" :rules="baseInfoRule" label-width="100px">
          <el-form-item label="商品名称" prop="spuName">
            <el-input style="width: 240px;" placeholder="请输入 商品名称" v-model="spu.spuName"></el-input>
          </el-form-item>
          <el-form-item label="商品描述">
            <el-input style="width: 240px;" placeholder="请输入 商品描述" v-model="spu.spuDescription"
                      type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="选择分类" prop="categoryId">
            <el-cascader
              placeholder="请选择 分类"
              style="width: 180px;"
              v-model="spu.categoryId"
              :options="categoryList"
              @change="handleChange"></el-cascader>
          </el-form-item>
          <el-form-item label="选择品牌" prop="brandId">
            <el-select style="width: 180px;" v-model="spu.brandId" placeholder="请选择 品牌">
              <el-option
                v-for="item in brandList"
                :key="item.brandId"
                :label="item.name"
                :value="item.brandId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品重量">
            <el-input-number v-model.number="spu.weight" :min="0" :precision="3" :step="0.1"/>
            <span style="margin-left: 8px; color: black; font-weight: 700;">Kg</span>
          </el-form-item>
          <!--<el-form-item label="设置积分">
            <label style="margin-right: 8px; color: #409eff;">金币:</label>
            <el-input-number
              placeholder="金币"
              v-model="spu.bounds.buyBounds"
              :min="0"
            />
            <label style="margin-left:15px; margin-right: 8px; color: #409eff;">成长值:</label>
            <el-input-number
              placeholder="成长值"
              v-model="spu.bounds.growBounds"
              :min="0"
            />
          </el-form-item>-->
          <el-form-item label="商品介绍" prop="description">
            <multi-upload v-model="spu.description"></multi-upload>
          </el-form-item>
          <el-form-item label="商品图集" prop="images">
            <multi-upload v-model="spu.images"></multi-upload>
          </el-form-item>
          <el-form-item>
            <el-button style="margin: 20px 0 0 120px;" @click="setBaseAttr" size="medium" type="primary">下一步: 设置基本参数
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {addSpu, fetchDetail, fetchList, putObj} from '@/api/spu';
import {fetchSkuList} from '@/api/sku';
import {spuTableOption, skuTableOption} from "@/const/crud/spu";
import {fetchCidTree} from "@/api/category";
import request from "@/router/axios";
import {brandList} from "@/api/brand";
import MultiUpload from "@/components/upload/multiUpload";

export default {
  name: "index",
  components: {
    MultiUpload
  },
  data() {
    return {
      page: {
        total: 0,
        pageSize: 10
      },
      skuPage: {
        total: 0,
        pageSize: 10
      },
      tableLoading: false,
      spuTableOption: spuTableOption,
      detailDialogVisible: false,
      skuDialogVisible: false,
      addSpuDialogVisible: false,
      editSpuDialogVisible: false,
      addSpuActive: 0,
      currentSpuId: 0,
      skuList: [],
      skuTableOption: skuTableOption,
      // 缩略图图册
      albumList: [],
      // 预览图册
      detailImgUrlList: [],
      spuList: [],
      skuMap: {},
      categoryList: [],
      brandList: [],
      baseAttrForm: {},
      saleAttrForm: {},
      tempSaleAttrs: [],
      spu: {
        //要提交的数据
        categoryId: "",
        spuName: "",
        spuDescription: "",
        brandId: "",
        weight: "",
        publishStatus: 0,
        description: [], //商品详情
        images: [], //商品图集，最后sku也可以新增
        bounds: {
          //积分
          buyBounds: 0,
          growBounds: 0
        },
        baseAttrs: [], //基本属性
        skus: [] //所有sku信息
      },
      // 自定义销售属性
      inputVisible: [],
      inputValue: [],
      generateSkuTable: [],
      baseInfoRule: {
        spuName: [
          {required: true, message: '请输入商品名称', trigger: 'blur'}
        ],
        categoryId: [
          {required: true, message: '请选择一个分类', trigger: 'change'}
        ],
        brandId: [
          {required: true, message: '请选择一个品牌', trigger: 'change'}
        ],
        description: [
          {required: false, message: '请上传商品详情图集', trigger: 'blur'}
        ],
        images: [
          {required: false, message: '请上传商品图片集', trigger: 'blur'}
        ]
      }
    }
  },
  created() {

  },
  methods: {
    getList(page, params) {
      this.tableLoading = true;
      params = {
        key: '',
        categoryId: null,
        brandId: null,
        status: null,
      }
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, params)).then(response => {
        this.spuList = response.data.data.list;
        this.page.total = response.data.data.totalCount;
        this.tableLoading = false;
      });
    },
    refreshChange() {
      this.getList()
    },
    handleShow(row, index) {
      fetchDetail(row.id).then(response => {
        this.detailImgUrlList = response.data.data;
      })
      this.detailDialogVisible = true;
    },
    // TODO 编辑待做 sku列表待做
    handleEdit(row, index) {
      // console.log(this.spuList[index]);
      // this.spu = this.spuList[index];
      this.editSpuDialogVisible = true;
    },
    handleDel(row, index) {
      this.$confirm('是否确认删除【' + row.spuName + '】商品', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        // TODO 删除待实现 可能需要将 sku一起删除
        return delObj(row.spuId)
      }).then(data => {
        this.$message.success('删除成功')
        this.getList()
      })
    },
    // 切换图册
    changeAlbum(row) {
      const list = [];
      row.imageList.forEach(item => {
        list.push(item.imgUrl);
      })
      this.albumList = list;
    },
    // 查看sku列表
    handleShowSKU(row, index) {
      this.currentSpuId = row.id;
      this.getSkuList({
        currentPage: 1,
        pageSize: 10
      });
    },
    // 获取sku列表
    getSkuList(page) {
      console.log(this.currentSpuId);
      fetchSkuList(this.currentSpuId, Object.assign({
        current: page.currentPage,
        size: page.pageSize
      })).then(response => {
        this.skuList = response.data.data.list;
        this.skuPage.total = response.data.data.totalCount;
      }).finally(() => {
        this.skuDialogVisible = true;
      })
    },

    // 修改上下架状态 TODO
    handleChangeStatus(row) {
      putObj(row).then(data => {
        this.$message.success('修改成功');
        this.getList(this.page)
      }).catch(() => {

      });
    },
    handleAddSpu() {
      this.addSpuActive = 0;
      this.addSpuDialogVisible = true;
      fetchCidTree(3).then(res => {
        this.categoryList = res.data.data;
      });
      brandList().then(response => {
        this.brandList = response.data.data;
      });
    },
    // 设置基本规格参数
    setBaseAttr() {
      console.log(this.spu.categoryId);
      this.$refs.spuBaseInfoForm.validate((valid) => {
        if (valid) {
          request({
            url: `/product/attr/base/all/${this.spu.categoryId}`,
            method: 'get'
          }).then(response => {
            this.baseAttrForm = response.data.data;
            this.spu.baseAttrs = response.data.data;
            this.addSpuActive = 1;
          });
        } else {
          return false;
        }
      });

    },
    // 设置销售属性
    setSaleAttr() {
      this.spu.categoryId = 225;
      this.spu.baseAttrs = [];
      this.baseAttrForm.forEach(group => {
        // 找到group下面的列
        group.column.forEach(attr => {
          let {attrId, attrValues, isShow} = attr;
          // 跳过没有录入值的属性
          console.log(attrValues);
          if (!(attrValues === "" || attrValues === undefined)) {
            if (attrValues instanceof Array) {
              // 多个值用;隔开
              attrValues = attrValues.join(";");
            }
            this.spu.baseAttrs.push({attrId, attrValues, isShow});
          }
        });
      });
      request({
        url: `/product/attr/sale/all/${this.spu.categoryId}`,
        method: 'get'
      }).then(response => {
        this.saleAttrForm = response.data.data;
        this.saleAttrForm.forEach(item => {
          this.tempSaleAttrs.push({
            attrId: item.attrId,
            attrValues: [],
            attrName: item.label
          });
          this.inputVisible.push({view: false});
          this.inputValue.push({val: ""});
        });
        this.addSpuActive = 2;
      });
    },
    // TODO 生成SKU列表并设置
    generateSku() {
      let selectValues = [];
      this.generateSkuTable = [];
      this.tempSaleAttrs.forEach(item => {
        if (item.attrValues.length > 0) {
          selectValues.push(item.attrValues);
          this.generateSkuTable.push(item)
        }
      });

      let descartes = this.descartes(selectValues);

      let skus = [];

      descartes.forEach((descar, descaridx) => {
        let attrArray = []; //sku属性组
        descar.forEach((de, index) => {
          //构造saleAttr信息
          let saleAttrItem = {
            attrId: this.generateSkuTable[index].attrId,
            attrName: this.generateSkuTable[index].attrName,
            attrValue: de
          };
          attrArray.push(saleAttrItem);
        });
        //先初始化几个images，后面的上传还要加
        let imgs = [];
        this.spu.images.forEach((img, idx) => {
          if (idx === 0) {
            imgs.push({imgUrl: img, defaultImg: 1});
          } else {
            imgs.push({imgUrl: img, defaultImg: 0});
          }
        });

        //;descaridx，判断如果之前有就用之前的值;
        let res = this.hasAndReturnSku(this.spu.skus, descar);
        if (res === null) {
          skus.push({
            attr: attrArray,
            skuName: this.spu.spuName + " " + descar.join(" "),
            // skuName: "",
            price: 0,
            skuTitle: this.spu.spuName + " " + descar.join(" "),
            // skuTitle: "",
            skuSubtitle: "",
            images: imgs,
            descartes: descar,
            fullCount: 0,
            discount: 0,
            countStatus: 0,
            fullPrice: 0.0,
            reducePrice: 0.0,
            priceStatus: 0
          });
        } else {
          skus.push(res);
        }
      })

      this.spu.skus = skus;
      console.log("结果!!!", this.spu.skus, this.generateSkuTable);

      this.addSpuActive = 3;

    },
    // 判断如果包含之前的sku的descar组合，就返回这个sku的详细信息；
    hasAndReturnSku(skus, descar) {
      let res = null;
      if (skus.length > 0) {
        for (let i = 0; i < skus.length; i++) {
          if (skus[i].descartes.join(" ") === descar.join(" ")) {
            res = skus[i];
          }
        }
      }
      return res;
    },
    submitSkus() {
      this.$confirm("将要提交商品数据，需要一小段时间，是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        addSpu(this.spu).then(response => {
          if (response.data.code === 0) {
            this.$message.success(response.data.msg);
            this.addSpuDialogVisible = false;
            this.getList(this.page);
          } else {
            this.$message.error(response.data.msg);
          }
        });
      });
    },
    handleChange(value) {
      this.spu.categoryId = value[2];
    },
    // 显示自定义输入
    showInput(sid) {
      this.inputVisible[sid].view = true;
    },
    handleInputConfirm(sid) {
      let inputValue = this.inputValue[sid].val.trim();
      if (this.saleAttrForm[sid].valueSelect.indexOf(inputValue) !== -1) {
        this.$message.error("该属性已存在! 请重新输入");
        return;
      }
      if (inputValue) {
        if (this.saleAttrForm[sid].valueSelect === "") {
          this.saleAttrForm[sid].valueSelect = inputValue;
        } else {
          this.saleAttrForm[sid].valueSelect += ";" + inputValue;
        }
      }
      this.inputVisible[sid].view = false;
      this.inputValue[sid].val = "";
    },
    checkDefaultImg(row, index, img) {
      console.log("默认图片", row, index);
      //这个图片被选中了，
      row.images[index].imgUrl = img; //默认选中
      row.images[index].defaultImg = 1; //修改标志位;
      //修改其他人的标志位
      row.images.forEach((item, idx) => {
        if (idx !== index) {
          row.images[idx].defaultImg = 0;
        }
      });
    },
    /**
     * 生成笛卡尔积
     * @param array
     * @returns {*|*[]}
     */
    descartes(array) {
      if (array.length < 2) {
        return array[0] || [];
      }
      return [].reduce.call(array, function (col, set) {
        const res = [];
        col.forEach(function (c) {
          set.forEach(function (s) {
            const t = [].concat(Array.isArray(c) ? c : [c]);
            t.push(s);
            res.push(t);
          })
        });
        return res;
      });
    }
  }
}
</script>

<style scoped>
</style>
